package com.iwayin.web.action;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.epistem.util.Base64;
import com.iwayin.core.bo.user.UserBO;
import com.iwayin.core.common.Constants;
import com.iwayin.core.dataobject.UserDO;
import com.iwayin.core.utils.DateTimeUtil;
import com.iwayin.core.utils.PasswordUtil;
import com.iwayin.web.common.AjaxResult;
import com.iwayin.web.common.EmailSender;

public class IndexAction extends BaseAction{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String myEmail;
	private AjaxResult ajaxResult;
	private UserDO user ;
	private UserBO userBO ;
	private String dt;
	private String emailHost;
	private String pwd;
	/**
	 * 发送重置密码email
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String processSendEmail() {
		//是否重复申请
		if(Constants.statusMap.containsKey(user.getLoginName())){
			String time = Constants.statusMap.get(user.getLoginName());
			Date requestTime = DateTimeUtil.getFormatDate(time, DateTimeUtil.TIME_FORMAT_OUT);
			//是否超过24小时
			if(DateTimeUtil.getDateBeforeOrAfter(-1).compareTo(requestTime) < 0){
				ajaxResult = AjaxResult.errorResult("24小时内只能使用一次找回密码!请查收您注册邮箱里的邮件 或 <a href='http://www.yoasking.com'>回首页</a>");
				return SUCCESS;
			} else {
				String curD = DateTimeUtil.getFormatDate(DateTimeUtil.getCurrDate(), DateTimeUtil.TIME_FORMAT_OUT);
				Constants.statusMap.put(user.getLoginName(), curD);
			}
		}
		UserDO currentUser = userBO.getUserByEmail(user.getLoginName());
		if (currentUser == null) {
			ajaxResult = AjaxResult.errorResult("邮箱地址错误：还没有注册");
			return SUCCESS;
		}
		myEmail = currentUser.getLoginName();
		String currentDate = DateTimeUtil.getFormatDate(new Date(), DateTimeUtil.TIME_FORMAT_OUT);
		String urlParam = Base64.encode((myEmail + ";" + currentDate).getBytes());
		Constants.statusMap.put(myEmail, currentDate);
		EmailSender.send(myEmail, "[优问网]找回您的密码", buildResetEmail(urlParam), "text/html");
		ajaxResult = AjaxResult.succResult();
		return SUCCESS;
	}
	
	private String buildResetEmail(String code){
		String url = "http://www.yoasking.com/resetPage.action?dt="+code;
		StringBuilder sb = new StringBuilder("亲爱的用户:<p>");
		sb.append("感谢您注册蘑菇街,请点击以下链接重置您的密码。<p>");
		sb.append("<a target='_blank' href='").append(url).append("'>").append(url).append("<a/><p>");
		sb.append("愿您在蘑菇街度过愉快的时光。<p>");
		sb.append("<a target='_blank' href='http://www.yoasking.com'>").append("优问网").append("<a/>");
		return sb.toString();
	}
	
	/**
	 * 重置密码
	 * 
	 * @return
	 */
	public String resetPage() {
		try {
			String descryStr = new String(Base64.decode(dt));
			String[] array = descryStr.split(";");
			String loginEmail = array[0];
			if(array.length < 2 || !checkEmailType(loginEmail)){
				return ERROR;
			}
			user = userBO.getUserByLoginName(loginEmail);
			if(user == null){
				return ERROR;
			}
		} catch (Exception e) {
			return ERROR;
		}
		return SUCCESS;
	}
	/*
	 * 判断邮箱格式
	 */
	private boolean checkEmailType(String email){
		Pattern p = Pattern.compile("^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$");
		Matcher m = p.matcher(email);
		return m.matches();
	}
	/**
	 * 去登陆页
	 * @return
	 */
	public String toLogin(){
		return SUCCESS;
	}
	/**
	 * 去注册页
	 * @return
	 */
	public String toRegist(){
		return SUCCESS;
	}
	/**
	 * 去激活页
	 * @return
	 */
	public String toJihuo(){
		String[] str = myEmail.split("@");
		if(str[1].contains("hotmail") || str[1].contains("live")){
			emailHost = "http://"+str[1];
		}else {
			emailHost = "http://mail."+str[1];
		}
		return SUCCESS;
	}
	/**
	 * 忘记密码页面
	 * @return
	 */
	public String toForget(){
		return SUCCESS;
	}
	/**
	 * 重置密码
	 * @return
	 */
	public String backPassword(){
		if (!Constants.statusMap.containsKey(user.getLoginName())) {
			ajaxResult = AjaxResult
					.errorResult("重置失败：原因可能是上次找回失效，试试<a href='/toForget.action'>重新找回密码</a> 或<a href='http://www.yoasking.com'>返回首页</a>");
			return SUCCESS;
		}
		try {
			String passwordKey = PasswordUtil.getRandomOperPassword();// 随机key
			user.setPwdKey(passwordKey);
			String encryptPassword = PasswordUtil.getEncyptedOperPassword(
					this.pwd, passwordKey);
			user.setLoginPwd(encryptPassword);// 加密后密码
			userBO.updatePassword(user);
			ajaxResult = AjaxResult.succResult();
		} catch (Exception e) {
			ajaxResult = AjaxResult.errorResult(Constants.DEFAULT_SYSTEM_ERROR_MSG);
		}
		return SUCCESS;
	}

	public String getMyEmail() {
		return myEmail;
	}
	public void setMyEmail(String myEmail) {
		this.myEmail = myEmail;
	}
	public AjaxResult getAjaxResult() {
		return ajaxResult;
	}
	public void setAjaxResult(AjaxResult ajaxResult) {
		this.ajaxResult = ajaxResult;
	}
	public UserDO getUser() {
		return user;
	}
	public void setUser(UserDO user) {
		this.user = user;
	}
	public void setUserBO(UserBO userBO) {
		this.userBO = userBO;
	}

	public String getDt() {
		return dt;
	}

	public void setDt(String dt) {
		this.dt = dt;
	}

	public String getEmailHost() {
		return emailHost;
	}

	public void setEmailHost(String emailHost) {
		this.emailHost = emailHost;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
}
